package chapter1;

import stdlib.StdOut;


public class exercises1_1_a {

	public static void main(String[] args) {
		ex_1_1_7();
		ex_1_1_12();
		ex_1_1_14();
		ex_1_1_16();
		ex_1_1_18();
	}

	private static void ex_1_1_7() {
		double t = 9.0;
		while (Math.abs(t - 9.0 / t) > .001)
			t = (9.0 / t + t) / 2.0;
		StdOut.printf("%.5f\n", t);
		// sqr(9.0)

		int sum = 0;
		for (int i = 1; i < 1000; i++)
			for (int j = 0; j < i; j++)
				sum++;
		StdOut.println(sum);
		// 1000 * 499 + 500

		sum = 0;
		for (int i = 1; i < 1000; i *= 2)
			for (int j = 0; j < i; j++)
				sum++;
		StdOut.println(sum);
		// 1, 2, 4, ..., 2^9 --> 2^10 - 1
	}

	private static void ex_1_1_12() {
		int[] a = new int[10];
		for (int i = 0; i < 10; i++)
			a[i] = 9 - i;

		for (int i = 0; i < 10; i++) {
			a[i] = a[a[i]];
		}
		for (int i = 0; i < 10; i++)
			System.out.println(a[i]);
	}

	private static void ex_1_1_14() {
		System.out.println((lg(100) == (int) (Math.log(100) / Math.log(2))));
		System.out.println((lg(1000) == (int) (Math.log(1000) / Math.log(2))));
		System.out
				.println((lg(10000) == (int) (Math.log(10000) / Math.log(2))));
		System.out.println((lg(128) == (int) (Math.log(128) / Math.log(2))));
	}

	private static int lg(int N) {
		int retVal = 0;
		while (N >= 2) {
			N = N / 2;
			retVal++;
		}
		System.out.println(N + " lg2 value is " + retVal);
		return retVal;
	}

	private static void ex_1_1_16() {
		System.out.println(exR1(6));
	}
	
	private static void ex_1_1_18()
	{
		System.out.println(mystery(2, 25));
		System.out.println(mystery(3, 11));
	}

	public static String exR1(int n) {
		if (n <= 0)
			return "";
		return exR1(n - 3) + n + exR1(n - 2) + n;
	}

	public static int mystery(int a, int b) {
		if (b == 0)
			return 0;
		if (b % 2 == 0)
			return mystery(a + a, b / 2);
		return mystery(a + a, b / 2) + a;
	}
}
